package com.b2c.util;

import exception.EmailException;
import com.b2c.properties.SendEmailProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

@Slf4j
@Component
public class SendEmailUtil {
    @Autowired
    private Configuration cfg;
    @Autowired
    private SendEmailProperties sendEmailProperties;
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    public SendEmailUtil() {
    }

    /**
     * 发送邮箱
     *
     * @param reciver
     * @param data
     * @throws IOException
     * @throws TemplateException
     */
    public void sendEmail(String reciver, HashMap<String, String> data) {
        try {
            // 构建一个邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // true表示构建一个可以带附件的邮件对象
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            // 设置邮件主题
            mimeMessageHelper.setSubject(sendEmailProperties.getTitle());
            // 设置邮件发送者
            mimeMessageHelper.setFrom(sendEmailProperties.getSendUserMail());
            // 设置邮件接收者，可以有多个接收者
            mimeMessageHelper.addTo(reciver);
            // 设置邮件发送日期
            mimeMessageHelper.setSentDate(new Date());
            // 设置邮件的正文
            mimeMessageHelper.setText(getText(data), true);

            // 发送邮件
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("send mail error{}",e.getMessage());
            throw new EmailException();
        }

    }

    /**
     * 将模版与数据结合
     *
     * @param data
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    private String getText(HashMap<String, String> data) throws IOException, TemplateException {
        Template qqEmailTemplate = cfg.getTemplate(sendEmailProperties.getQqEmailTemplateName());
        return FreeMarkerTemplateUtils.processTemplateIntoString(qqEmailTemplate, data);
    }

}
